package com.server.service;

import com.server.entity.UserCode;
import com.server.example.UserCodeExample;
import com.server.mapper.UserCodeMapper;
import com.untils.MybatisClass;
import com.untils.StaticValues;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

/**
 * @author Admin
 */
public class PhoneCodeService {

    /**
     * 得到用户的手机验证码
     * @param userphoneInformation 手机号
     * @return  得到用户的手机验证码
     */
    public String setPhoneCode(String userphoneInformation){
        // 用户手机验证码 和有效时间相关
        String phoneCode = String.valueOf((int)(Math.random()*9000+1000));
        long time = System.currentTimeMillis();
        time += StaticValues.PHONE_CODE_TIMEOUT*1000*60;
        Date date = new Date(time);
        // 后端处理相关
        SqlSession sqlSession = MybatisClass.getSqlSession();
        UserCodeMapper userCodeMapper = sqlSession.getMapper(UserCodeMapper.class);
        int sauces;
        UserCode userCode = new UserCode();
        userCode.setUserCodeCode(phoneCode);
        userCode.setPhone(userphoneInformation);
        userCode.setUserCodeTime(date);
        try {
            sauces=userCodeMapper.insertSelective(userCode);
            sqlSession.commit();
            sqlSession.close();
            return String.valueOf(sauces);
        }catch (Exception e) {
            e.printStackTrace();
            sqlSession.close();
            return String.valueOf(-1);
        }
    }

    /**
     * 验证用户的手机验证码,true 验证通过，fals 验证失败
     * @param userphoneInformation 手机号
     * @return 验证用户的手机验证码
     */
    public Boolean getPhoneCode(String userphoneInformation,String phoneCode){
        SqlSession sqlSession = MybatisClass.getSqlSession();
        UserCodeMapper userCodeMapper = sqlSession.getMapper(UserCodeMapper.class);
        UserCodeExample userCodeExample = new UserCodeExample();
        boolean isSuccessfully;
        UserCode userCode = new UserCode();
        userCode.setUserCodeCode(phoneCode);
        userCode.setPhone(userphoneInformation);
        try {
            userCodeExample.createCriteria().andPhoneEqualTo(userCode.getPhone()).andUserCodeCodeEqualTo(userCode.getUserCodeCode());
            List<UserCode> userCodes=userCodeMapper.selectByExample(userCodeExample);
            System.out.println(userCodes.get(userCodes.size()-1).getUserCodeTime());
            if (userCodes.get(userCodes.size()-1).getUserCodeTime().getTime()>System.currentTimeMillis() && userCodes.size() > 0) {
                isSuccessfully=true;
            }else {
                isSuccessfully=false;
            }
        }catch (Exception e) {
            isSuccessfully=false;
        }finally {
            sqlSession.close();
        }
        return isSuccessfully;
    }
}
